﻿#include "systemsetting_2.h"
#include "ui_systemsetting_2.h"

Systemsetting_2::Systemsetting_2(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Systemsetting_2)
{
    ui->setupUi(this);
    time = new QLabel(ui->frameBottom);
    time->setGeometry(10, 10, 200, 40);
    time->setStyleSheet("QLabel{font: 20px; color: rgb(25, 25, 112);}");
    signal = new QLabel(ui->frameBottom);
    signal->setGeometry(700, 18, 41, 22);
    signal->setStyleSheet("QLabel{background-color:transparent;}");

    QDir dir(IMAGE_PATH);
    if(dir.exists())
    {
        ui->frameTop->setStyleSheet(LOGO_STY);
    }
//    ui->frameTop->setStyleSheet("QFrame{background-image : url(/usr/local/sanway/image/logo.png); background-repeat: no-repeat; }");

    ui->labelSystem2Hint->hide();
    ui->frameEnKeyBord->hide();

    QRegExp regExpIp("^(((\\d?\\d)|(1[0-9][0-9])|(2[0-4]\\d)|(25[0-5]))[.]){3}((\\d?\\d)|(1\\d\\d)|(2[0-4]\\d)|(25[0-5]))$");

    QValidator* validatorIp = new QRegExpValidator(regExpIp, 0);

//    ui->m_editRemoteIP->setValidator(validatorIp);
    ui->m_editLocalIP->setValidator(validatorIp);
    ui->m_editLocalIP->setValidator(validatorIp);
    ui->m_editNetMask->setValidator(validatorIp);
    ui->m_editGateWay->setValidator(validatorIp);
    ui->m_editDNS_1->setValidator(validatorIp);
    ui->m_editDNS_2->setValidator(validatorIp);


    QRegExp regExpPort("^(([1-9]\\d{3})|([1-5]\\d{4})|(6[0-4]\\d{3})|(65[0-4]\\d{2})|(655[0-2]\\d)|(6553[0-5]))$");
    QValidator* validatorRegExp = new QRegExpValidator(regExpPort, 0);

    ui->m_editPort->setValidator(validatorRegExp);

    QRegExp regExpInterfaceID("^([0-9a-f]{9})");   // 9位数字
    QRegExp regExpToken("^(([0-9a-zA-Z]){16})");  // 16位字母数字
    QValidator* validatorInterfaceID = new QRegExpValidator(regExpInterfaceID, 0);
    QValidator* validatorToken = new QRegExpValidator(regExpToken, 0);

    ui->m_editID->setValidator(validatorInterfaceID);
    ui->m_editToken->setValidator(validatorToken);

    interface = QNetworkInterface::interfaceFromName("eth0");
    devNetinfoModel = new QStandardItemModel(this);
    devNetinfoModel->setColumnCount(8);
    devNetinfoModel->setRowCount(1);
    devNetmapper = new QDataWidgetMapper(this);
    devNetmapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);//每当小部件失去焦点时，就将小部件的当前值设置为item模型。
    QStandardItem* root = devNetinfoModel->invisibleRootItem();
    QStandardItem* serIP = new QStandardItem(readFile(QString("/usr/local/sanway/dbTest/charge.conf"), QString("server_ip")));
    QStandardItem* netmask = new QStandardItem(interface.addressEntries().at(0).netmask().toString());
    QStandardItem* serport = new QStandardItem(readFile(QString("/usr/local/sanway/dbTest/charge.conf"), QString("server_port")));
    QStandardItem* gateway = new QStandardItem(readFile(QString("/usr/local/sanway/ini/system.ini"), QString("IP_GATEWAY0")));
    QStandardItem* devIP = new QStandardItem(interface.addressEntries().at(0).ip().toString()) ;
    QStandardItem* mac = new QStandardItem(interface.hardwareAddress());
    QStandardItem* interfaceID  = new QStandardItem(readFile(QString("/usr/local/sanway/dbTest/charge.conf"), QString("INTERFACE_ID")));
    QStandardItem* token = new QStandardItem(readFile(QString("/usr/local/sanway/dbTest/charge.conf"), QString("TOKEN")));
    root->setChild(0,0,serIP);
    root->setChild(0,1,netmask);
    root->setChild(0,2,serport);
    root->setChild(0,3,gateway);
    root->setChild(0,4,devIP);
    root->setChild(0,5,mac);
    root->setChild(0,6,interfaceID);
    root->setChild(0,7,token);
    devNetmapper->setModel(devNetinfoModel);
    devNetmapper->addMapping(ui->m_editRemoteIP, 0);
    devNetmapper->addMapping(ui->m_editNetMask, 1);
    devNetmapper->addMapping(ui->m_editPort, 2);
    devNetmapper->addMapping(ui->m_editGateWay, 3);
    devNetmapper->addMapping(ui->m_editLocalIP, 4);
    devNetmapper->addMapping(ui->m_editMacAddr, 5);
    devNetmapper->addMapping(ui->m_editID, 6);
    devNetmapper->addMapping(ui->m_editToken, 7);
    devNetmapper->toFirst();

    catchmouse_ = new QTimer(this);
    connect(catchmouse_, SIGNAL(timeout()), this, SLOT(catchpos_()));

    keyBoardConnect();
    connect(stackLayout,SIGNAL(currentChanged(int)),this,SLOT(show_net_info(int)));
    ENkey_board_released();
}

void Systemsetting_2::show_net_info(int current)
{
    if(current == SystemSetting2Page)
    {
        index = devNetinfoModel->index(0, 0);
        devNetinfoModel->setData(index, readFile(QString(CHARGE_CONF), QString("server_ip")), Qt::EditRole);
        index = devNetinfoModel->index(0, 1);
        devNetinfoModel->setData(index, interface.addressEntries().at(0).netmask().toString(), Qt::EditRole);
        index = devNetinfoModel->index(0, 2);
        devNetinfoModel->setData(index, readFile(QString(CHARGE_CONF), QString("server_port")), Qt::EditRole);
        index = devNetinfoModel->index(0, 3);
        devNetinfoModel->setData(index, readFile(QString(SYSTEM_INI), QString("IP_GATEWAY0")), Qt::EditRole);
        index = devNetinfoModel->index(0, 4);
        devNetinfoModel->setData(index, interface.addressEntries().at(0).ip().toString(), Qt::EditRole);
        index = devNetinfoModel->index(0, 5);
        devNetinfoModel->setData(index, interface.hardwareAddress(), Qt::EditRole);
        showDNS();
        index = devNetinfoModel->index(0, 6);
        devNetinfoModel->setData(index, readFile(QString(CHARGE_CONF), QString("INTERFACE_ID")), Qt::EditRole);
        index = devNetinfoModel->index(0, 7);
        devNetinfoModel->setData(index, readFile(QString(CHARGE_CONF), QString("TOKEN")), Qt::EditRole);
    }
}

void Systemsetting_2::on_buttonBack_clicked()
{
    stackLayout->setCurrentIndex(ChooseGunPage);
}

void Systemsetting_2::on_buttonPrev_clicked()
{
    stackLayout->setCurrentIndex(SystemSetting1Page);
}

void Systemsetting_2::on_buttonNext_clicked()
{
    stackLayout->setCurrentIndex(SystemSetting3Page);
}

void Systemsetting_2::on_buttonSave_clicked()
{
    //远程IP
    bool ret0 = writeFile(QString(CHARGE_CONF), QString("server_ip"), ui->m_editRemoteIP->text());
    if(ret0)
    {
       chargingData->cmd1.flag_change = 0;
    }

    //端口号;
    bool ret1 = writeFile(QString(CHARGE_CONF), QString("server_port"), ui->m_editPort->text());
    if(ret1)
    {
       chargingData->cmd1.flag_change = 0;
    }

    //本机IP
    bool ret2 = write_profile_string("ETH_SET", "IP_ADDR0", ui->m_editLocalIP->text().toAscii().constData(), SYSTEM_INI );
    QString ipSet = QString("ifconfig eth0 ") + ui->m_editLocalIP->text();
    system(ipSet.toLocal8Bit().constData());

    if(ret2 == 1)
    {
        chargingData->cmd1.flag_change = 0;
    }

    //系统设置中子网掩码的设置;
    int ret3 = 0;
    if(!ui->m_editNetMask->text().isEmpty())
    {
        QString NetMask = ui->m_editNetMask->text();
        ret3 = write_profile_string("ETH_SET", "IP_NETMASK0", NetMask.toAscii().constData(), SYSTEM_INI);
        if(ret3 == 1)
        {
            chargingData->cmd1.flag_change = 0;
        }
    }

    //默认网关的设置:
    int ret4 = 0;
    if(!ui->m_editGateWay->text().isEmpty())
    {
        QString GateWay = ui->m_editGateWay->text();
        ret4 = write_profile_string("ETH_SET", "IP_GATEWAY0", GateWay.toAscii().constData(), SYSTEM_INI);
        if(ret4 == 1)
        {
            chargingData->cmd1.flag_change = 0;
        }
    }

    //mac地址设置
    int ret5 = 0;
    if(!ui->m_editMacAddr->text().isEmpty())
    {
        QString MacAddr = ui->m_editMacAddr->text();
         ret5 = write_profile_string("MAC_SET", "MAC_ADDR0", MacAddr.toAscii().constData(), SYSTEM_INI);
        if(ret5 == 1)
        {
            chargingData->cmd1.flag_change = 0;
        }
    }
    // DNS
    int ret6 = 0;
    if(ui->m_editDNS_1->text().trimmed() != DNSlist.at(0).trimmed() ||
            ui->m_editDNS_2->text().trimmed() != DNSlist.at(1).trimmed())
    {
        QFile file("/etc/resolv.conf");
        if(file.exists())
        {
            if(file.open(QFile::WriteOnly | QFile::Truncate))
            {
                qDebug("打开并清空成功\n");
                file.close();
            }
            if(file.open(QFile::WriteOnly | QIODevice::Text))
            {
                qDebug("开始写入");
                QString in = "nameserver " + ui->m_editDNS_1->text().trimmed() + "\n"
                        + "nameserver " + ui->m_editDNS_2->text().trimmed();
                QTextStream out(&file);
                out << in << "\n";
                file.close();
                ret6 = 1;
            }
        }
    }

    // interface_id
    bool ret7 = writeFile(QString(CHARGE_CONF), QString("INTERFACE_ID"), ui->m_editID->text());
    if(ret7)
    {
       chargingData->cmd1.flag_change = 0;
    }

    // token
    bool ret8 = writeFile(QString(CHARGE_CONF), QString("TOKEN"), ui->m_editToken->text());
    if(ret8)
    {
       chargingData->cmd1.flag_change = 0;
    }

    if(ret0 && ret1 && ret2 && ret3 && ret4 && ret5 && ret6 & ret7 && ret8)
    {
        ui->labelSystem2Hint->setText(tr("设置成功"));
        ui->labelSystem2Hint->show();
        QTimer::singleShot(3000,ui->labelSystem2Hint,SLOT(hide()));//显示三秒后隐藏
    }
    else
    {
        ui->labelSystem2Hint->setText(tr("设置失败"));
        ui->labelSystem2Hint->show();
        QTimer::singleShot(3000,ui->labelSystem2Hint,SLOT(hide()));//显示三秒后隐藏
    }
    /*待完成*/
}

void Systemsetting_2::keyHandle(QPushButton* btn, QLineEdit* lineEdit)
{
    if(btn->text() == tr("退格"))
    {
        lineEdit->backspace();
    }
    else if( btn->text() == tr("清除"))
    {
        lineEdit->clear();
    }
    else
    {
        lineEdit->insert(btn->text());
    }
}

void Systemsetting_2::on_Keyboard_clicked()
{
    QPushButton* btn =  static_cast<QPushButton*>(sender());

    QLineEdit* focus = (QLineEdit* )QApplication::focusWidget();

    keyHandle(btn, focus);

}
void Systemsetting_2::keyBoardConnect()
{
    connect(ui->One, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
    connect(ui->Tow, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
    connect(ui->Three, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
    connect(ui->Four, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
    connect(ui->Five, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
    connect(ui->Six, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
    connect(ui->Seven, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
    connect(ui->Eight, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
    connect(ui->Nine, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
    connect(ui->Zero, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
    connect(ui->Remove, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
    connect(ui->RemoveAll, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
//    connect(ui->Char1, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
//    connect(ui->Char2, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
    connect(ui->Char3, SIGNAL(clicked()), this, SLOT(on_Keyboard_clicked()));
}
void Systemsetting_2::ENkey_board_released()
{
    connect(ui->OneEN, SIGNAL(pressed()), this, SLOT(EN_pressed_slot()));
    connect(ui->TowEN, SIGNAL(pressed()), this, SLOT(EN_pressed_slot()));
    connect(ui->ThreeEN, SIGNAL(pressed()), this, SLOT(EN_pressed_slot()));
    connect(ui->FourEN, SIGNAL(pressed()), this, SLOT(EN_pressed_slot()));
    connect(ui->FiveEN, SIGNAL(pressed()), this, SLOT(EN_pressed_slot()));
    connect(ui->SixEN, SIGNAL(pressed()), this, SLOT(EN_pressed_slot()));
    connect(ui->SevenEN, SIGNAL(pressed()), this, SLOT(EN_pressed_slot()));
    connect(ui->EightEN, SIGNAL(pressed()), this, SLOT(EN_pressed_slot()));
    connect(ui->NineEN, SIGNAL(pressed()), this, SLOT(EN_pressed_slot()));
    connect(ui->ZeroEN, SIGNAL(pressed()), this, SLOT(EN_pressed_slot()));

    connect(ui->OneEN, SIGNAL(released()), this, SLOT(EN_released_slot()));
    connect(ui->TowEN, SIGNAL(released()), this, SLOT(EN_released_slot()));
    connect(ui->ThreeEN, SIGNAL(released()), this, SLOT(EN_released_slot()));
    connect(ui->FourEN, SIGNAL(released()), this, SLOT(EN_released_slot()));
    connect(ui->FiveEN, SIGNAL(released()), this, SLOT(EN_released_slot()));
    connect(ui->SixEN, SIGNAL(released()), this, SLOT(EN_released_slot()));
    connect(ui->SevenEN, SIGNAL(released()), this, SLOT(EN_released_slot()));
    connect(ui->EightEN, SIGNAL(released()), this, SLOT(EN_released_slot()));
    connect(ui->NineEN, SIGNAL(released()), this, SLOT(EN_released_slot()));
    connect(ui->ZeroEN, SIGNAL(released()), this, SLOT(EN_released_slot()));
}
void Systemsetting_2::EN_pressed_slot()
{
    btn =  static_cast<QPushButton*>(sender());
    released_text = btn->text().remove("\n");
    catchmouse_->start(10);
}
void Systemsetting_2::EN_released_slot()
{
    catchmouse_->stop();
    QLineEdit* focus = (QLineEdit* )QApplication::focusWidget();
    focus->insert(ui->ShowEN->text());
    ui->ShowEN->clear();
}
void Systemsetting_2::catchpos()
{
}
void Systemsetting_2::catchpos_()
{
    coursePoint = btn->mapFromGlobal(QCursor::pos());
    if(released_text.length() == 3)
    {
        switch(coursePoint.x()/20)
        {
        case 0:
            ui->ShowEN->setText(released_text.at(0));
            break;
        case 1:
            ui->ShowEN->setText(released_text.at(1));
            break;
        case 2:
            ui->ShowEN->setText(released_text.at(2));
            break;
        }
    }
    else if(released_text.length() == 4)
    {
        switch(coursePoint.x()/15)
        {
        case 0:
            ui->ShowEN->setText(released_text.at(0));
            break;
        case 1:
            ui->ShowEN->setText(released_text.at(1));
            break;
        case 2:
            ui->ShowEN->setText(released_text.at(2));
            break;
        case 3:
            ui->ShowEN->setText(released_text.at(3));
            break;
        }
    }
}
Systemsetting_2::~Systemsetting_2()
{
    delete ui;
}
void Systemsetting_2::showDNS()
{
    QString strDNS;
    QFile file("/etc/ppp/resolv.conf");
    if(file.exists())
    {
        if(file.open(QIODevice::ReadOnly))
        {
            qDebug("打开成功\n");
            QByteArray t = file.readAll();
            strDNS = QString (t);
            strDNS = strDNS.remove("nameserver");
            qDebug()<<"strDNS>>>"<<strDNS<<"<<<strDNS";
            DNSlist = strDNS.split("\n");
            qDebug()<<DNSlist;
            if(!DNSlist.count() == 2){
                ui->m_editDNS_1->setText(DNSlist.at(0));
                ui->m_editDNS_2->setText(DNSlist.at(1));
            }

            file.close();
        }
    }
}
void Systemsetting_2::on_buttonBoardswitch_clicked()
{
    if(ui->frameEnKeyBord->isHidden())
    {
        ui->frameEnKeyBord->show();
        ui->frameKeyBord->hide();
    }
    else
    {
        ui->frameKeyBord->show();
        ui->frameEnKeyBord->hide();
    }
}

void Systemsetting_2::on_Char3_2_clicked()
{
    QLineEdit* focus = (QLineEdit* )QApplication::focusWidget();
    focus->insert(ui->Char3_2->text());
}

void Systemsetting_2::on_Char1_2_clicked()
{
    QLineEdit* focus = (QLineEdit* )QApplication::focusWidget();
    focus->insert(ui->Char1_2->text());
}

void Systemsetting_2::on_Char2_2_clicked()
{
    QLineEdit* focus = (QLineEdit* )QApplication::focusWidget();
    focus->insert(ui->Char2_2->text());
}

void Systemsetting_2::on_RemoveAll_2_clicked()
{
    QLineEdit* focus = (QLineEdit* )QApplication::focusWidget();
    focus->clear();
}

void Systemsetting_2::on_Remove_2_clicked()
{
    QLineEdit* focus = (QLineEdit* )QApplication::focusWidget();
    focus->backspace();
}
